﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using FITClub.TextureMenu;
using Microsoft.Xna.Framework.Graphics;

#if WINDOWS

using System.ComponentModel;

#endif

namespace FITClub.Episode1.Configuration
{
    public enum ModelPresetType
    {
        Character, Level, AnyModel, AnyTexture
    }

    /// <summary>
    /// Stores paths to level preview, character model and other textures.
    /// </summary>
    [XmlInclude(typeof(TextureItem))]
#if WINDOWS
    [Serializable]
#endif
    public class ModelPreset : ILoadable
    {
        [XmlAttribute]
        public string ModelName { get; set; }

        [XmlElement]
        public string Param { get; set; }

        [XmlAttribute]
        public string PreviewPath { get; set; }

        [XmlAttribute]
        public ModelPresetType PresetType { get; set; }

        [XmlArrayItem(ElementName = "TextureItem", Type = typeof(TextureItem))]
        public List<TextureItem> Textures { get; set; }

        public ModelPreset()
        {
            this.Textures = new List<TextureItem>();
        }

#if WINDOWS

        [Browsable(false)]
#endif
        [XmlIgnore]
        public Texture2D Preview { get { return this.preview; } }

        public TextureItem this[string meshId]
        {
            get { return this.Textures.Single((TextureItem p) => p.MeshId == meshId); }
        }

        public TextureItem this[int meshId]
        {
            get { return this.Textures[meshId]; }
        }

        public void LoadContent(Microsoft.Xna.Framework.Content.ContentManager loader)
        {
            if (ContentLoaded == false)
            {
                if (this.PreviewPath != null && this.PreviewPath.Trim() != string.Empty) this.preview = loader.Load<Texture2D>(this.PreviewPath);
                this.Textures.ForEach((TextureItem itm) => itm.LoadContent(loader));
                this.ContentLoaded = true;
            }
        }

#if WINDOWS

        [Browsable(false)]
#endif
        [XmlIgnore]
        public bool ContentLoaded { get; set; }

#if WINDOWS
        [NonSerialized]
#endif
        private Texture2D preview;

        public void Dispose()
        {
            if (ContentLoaded == true)
            {
                if (this.Preview != null) this.Preview.Dispose();
                this.Textures.ForEach((TextureItem itm) => itm.Dispose());
                this.ContentLoaded = false;
            }
        }

        public override string ToString()
        {
            return string.Format("ModelPreset={0}, Textures={1}", this.ModelName, this.Textures.Count);
        }
    }
}